// DailySettlementPanel.java 日结操作界面
package com.dw.gui.panel.fee;

import com.dw.dao.fee.DailySettlementDao;
import com.dw.dao.fee.RefundRecordDao;
import com.dw.dao.invoice.InvoiceDao;
import com.dw.model.fee.DailySettlement;
import com.dw.model.user.Doctor;
import com.dw.util.UIUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DailySettlementPanel extends JPanel {
    private final Doctor doctor;
    private JLabel lblLastSettleTime;
    private JLabel lblTodayIncome;
    private JLabel lblTodayRefund;
    private JTextField tfCashAmount;
    private JTextArea taRemark;

    private DailySettlement currentSettlement;

    public DailySettlementPanel(Doctor doctor) {
        this.doctor = doctor;
        initUI();
        loadLastSettlement();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setBackground(Color.WHITE);
        titlePanel.add(UIUtil.createTitleLabel("费用日结"));
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 统计信息面板
        JPanel statsPanel = new JPanel(new GridBagLayout());
        statsPanel.setBackground(Color.WHITE);
        statsPanel.setBorder(BorderFactory.createTitledBorder("本日统计"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 最后日结时间
        gbc.gridx = 0;
        gbc.gridy = 0;
        statsPanel.add(UIUtil.createLabel("最后日结时间："), gbc);
        gbc.gridx = 1;
        lblLastSettleTime = UIUtil.createLabel("加载中...");
        statsPanel.add(lblLastSettleTime, gbc);

        // 本日收入
        gbc.gridx = 0;
        gbc.gridy = 1;
        statsPanel.add(UIUtil.createLabel("本日总收入："), gbc);
        gbc.gridx = 1;
        lblTodayIncome = UIUtil.createLabel("");
        statsPanel.add(lblTodayIncome, gbc);

        // 本日退费
        gbc.gridx = 0;
        gbc.gridy = 2;
        statsPanel.add(UIUtil.createLabel("本日总退费："), gbc);
        gbc.gridx = 1;
        lblTodayRefund = UIUtil.createLabel("");
        statsPanel.add(lblTodayRefund, gbc);

        // 输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        inputPanel.setBackground(Color.WHITE);
        inputPanel.setBorder(BorderFactory.createTitledBorder("结算信息"));

        gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        inputPanel.add(UIUtil.createLabel("现金金额："), gbc);

        gbc.gridx = 1;
        tfCashAmount = UIUtil.createTextField();
        tfCashAmount.setPreferredSize(new Dimension(200, 25)); // 固定高度
        inputPanel.add(tfCashAmount, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridheight = 2;
        gbc.fill = GridBagConstraints.BOTH;
        inputPanel.add(UIUtil.createLabel("备注说明："), gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        taRemark = UIUtil.createTextArea(3, 20);
        inputPanel.add(new JScrollPane(taRemark), gbc);

        // 操作按钮
        JButton btnSettle = UIUtil.createButton("执行日结");
        btnSettle.addActionListener(this::performSettlement);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.add(btnSettle);

        // 主内容面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        mainPanel.add(statsPanel, BorderLayout.NORTH);
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(titlePanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
    }

    private void loadLastSettlement() {
        new SwingWorker<Void, Void>() {
            DailySettlement last;
            BigDecimal todayIncome;
            BigDecimal todayRefund;

            @Override
            protected Void doInBackground() throws Exception {
                DailySettlementDao dao = new DailySettlementDao();
                last = dao.getLastSettlement();
                todayIncome = new InvoiceDao().getDailyTotal();
                todayRefund = new RefundRecordDao().getDailyRefundTotal();
                return null;
            }

            @Override
            protected void done() {
                try {
                    // 更新最后日结时间
                    if (last != null && last.getSettleDate() != null) {
                        lblLastSettleTime.setText(last.getSettleDate()
                                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    } else {
                        lblLastSettleTime.setText("暂无历史记录");
                    }

                    // 更新当日统计
                    lblTodayIncome.setText(formatCurrency(todayIncome));
                    lblTodayRefund.setText(formatCurrency(todayRefund));
                } catch (Exception e) {
                    UIUtil.showError(DailySettlementPanel.this,
                            "数据加载失败：" + e.getMessage(), "系统错误");
                }
            }
        }.execute();
    }
    private String formatCurrency(BigDecimal amount) {
        return "¥" + amount.setScale(2, RoundingMode.HALF_UP);
    }

    private void performSettlement(ActionEvent e) {
        // 验证现金金额输入
        String cashAmountText = tfCashAmount.getText().trim();
        if (cashAmountText.isEmpty()) {
            UIUtil.showError(this, "现金金额不能为空", "输入错误");
            tfCashAmount.requestFocus();
            return;
        }

        try {
            BigDecimal cashAmount = new BigDecimal(cashAmountText);
            if (cashAmount.compareTo(BigDecimal.ZERO) < 0) {
                UIUtil.showError(this, "现金金额不能为负数", "输入错误");
                return;
            }

            // 使用SwingWorker执行后台操作
            new SwingWorker<Boolean, Void>() {
                private DailySettlement ds;

                @Override
                protected Boolean doInBackground() throws Exception {
                    // 获取当日数据
                    BigDecimal total = new InvoiceDao().getDailyTotal();
                    BigDecimal refunds = new RefundRecordDao().getDailyRefundTotal();
                    int invoiceCount = new InvoiceDao().getDailyCount();

                    // 创建日结记录
                    ds = new DailySettlement();
                    ds.setSettlementNo("DS" + System.currentTimeMillis());
                    ds.setSettleDate(LocalDateTime.now());
                    ds.setTotalAmount(total);
                    ds.setRefundAmount(refunds);
                    ds.setCashAmount(cashAmount);
                    ds.setInvoiceCount(invoiceCount);
                    ds.setOperatorId(doctor.getId());
                    ds.setRemark(taRemark.getText().trim());

                    return new DailySettlementDao().createSettlement(ds);
                }

                @Override
                protected void done() {
                    try {
                        if (get()) {
                            currentSettlement = ds;
                            UIUtil.showInfo(DailySettlementPanel.this,
                                    "日结操作成功完成\n结算单号：" + ds.getSettlementNo(), "操作成功");

                            // 清空输入并刷新数据
                            EventQueue.invokeLater(() -> {
                                tfCashAmount.setText("");
                                taRemark.setText("");
                                loadLastSettlement();
                            });
                        }
                    } catch (java.util.concurrent.ExecutionException e) {
                        Throwable cause = e.getCause();
                        if (cause instanceof SQLException) {
                            UIUtil.showError(DailySettlementPanel.this,
                                    "数据库错误：" + cause.getMessage(), "日结失败");
                        } else if (cause instanceof NumberFormatException) {
                            UIUtil.showError(DailySettlementPanel.this,
                                    "金额格式错误：" + cause.getMessage(), "输入错误");
                        } else {
                            UIUtil.showError(DailySettlementPanel.this,
                                    "系统错误：" + cause.getMessage(), "日结失败");
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } catch (Exception e) {
                        UIUtil.showError(DailySettlementPanel.this,
                                "未知错误：" + e.getMessage(), "日结失败");
                    }
                }
            }.execute();

        } catch (NumberFormatException ex) {
            UIUtil.showError(this, "请输入有效的金额格式（示例：123.45）", "格式错误");
            tfCashAmount.requestFocus();
            tfCashAmount.selectAll();
        }
    }
}